﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.IO;


namespace Deeper.Common
{
	public static class FileNameHelper
	{
		/// <summary>
		/// 获取随机的上传文件名称
		/// </summary>
		/// <param name="srcFileName">源文件名</param>
		/// <param name="destPath">目标路径</param>
		/// <returns></returns>
		public static string GetRandomFileName(this string srcFileName, string destPath)
		{
			string ftype = srcFileName.Substring(srcFileName.LastIndexOf(".") + 1);
			string path = string.Format("{0}{1}\\", destPath, DateTime.Now.ToString("yyyyMM"));
			if (!System.IO.Directory.Exists(path))
				System.IO.Directory.CreateDirectory(path);
			///生成随机文件
			string fullname = string.Format("{0}{1}.{2}", path, DateTime.Now.ToString("yyyyMMddhhmmssffffff"), ftype);
			return fullname;
		}
	}

	public class ImageHelper
	{


		/// <summary>
		/// A better alternative to Image.GetThumbnail. Higher quality but slightly slower
		/// </summary>
		/// <param name="source"></param>
		/// <param name="thumbWi"></param>
		/// <param name="thumbHi"></param>
		/// <returns></returns>
		public static Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi, bool maintainAspect)
		{
			// return the source image if it's smaller than the designated thumbnail
			if (source.Width < thumbWi && source.Height < thumbHi) return source;

			System.Drawing.Bitmap ret = null;
			try
			{
				int wi, hi;

				wi = thumbWi;
				hi = thumbHi;

				if (maintainAspect)
				{
					// maintain the aspect ratio despite the thumbnail size parameters
					if (source.Width > source.Height)
					{
						wi = thumbWi;
						hi = (int)(source.Height * ((decimal)thumbWi / source.Width));
					}
					else
					{
						hi = thumbHi;
						wi = (int)(source.Width * ((decimal)thumbHi / source.Height));
					}
				}

				// original code that creates lousy thumbnails
				// System.Drawing.Image ret = source.GetThumbnailImage(wi,hi,null,IntPtr.Zero);
				ret = new Bitmap(wi, hi);
				using (Graphics g = Graphics.FromImage(ret))
				{
					g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					g.FillRectangle(Brushes.White, 0, 0, wi, hi);
					g.DrawImage(source, 0, 0, wi, hi);
				}
			}
			catch
			{
				ret = null;
			}

			return ret;
		}


		/// <summary>
		/// 缩略方式
		/// </summary>

		public enum ThumbnailMode
		{
			/// <summary>
			/// 指定高度，宽度自动适应
			/// </summary>
			AutoWith,
			/// <summary>
			/// 指定宽度，高度自动适应
			/// </summary>
			AutoHeight,
			/// <summary>
			/// 根据指定高宽剪裁不变形
			/// </summary>
			Cut,
			/// <summary>
			/// 指定高宽，图形可能变形
			/// </summary>
			AutoFit
		}

		/// <summary>
		/// 判断文件名是否为浏览器可以直接显示的图片文件名
		/// </summary>
		/// <param name="filename">文件名</param>
		/// <returns>是否可以直接显示</returns>
		public static bool IsImgFilename(string filename)
		{
			filename = filename.Trim();
			if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
			{
				return false;
			}
			string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
			return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
		}


		#region 给图片加水印
		/// <summary>
		/// 添加水印
		/// </summary>
		/// <param name="oldpath">原图片绝对地址</param>
		/// <param name="newpath">新图片放置的绝对地址</param>
		/// <param name="wmtType">要添加的水印的类型</param>
		/// <param name="sWaterMarkContent">水印内容，若添加文字水印，此即为要添加的文字；
		public static void addWaterMark(string oldpath, string newpath, string sWaterMarkContent)
		{
			try
			{
				Image image = Image.FromFile(oldpath);

				Bitmap b = new Bitmap(image.Width, image.Height,
					PixelFormat.Format24bppRgb);

				Graphics g = Graphics.FromImage(b);
				g.Clear(Color.White);
				g.SmoothingMode = SmoothingMode.HighQuality;
				g.InterpolationMode = InterpolationMode.High;

				g.DrawImage(image, 0, 0, image.Width, image.Height);

				addWatermarkText(g, sWaterMarkContent, "WM_BOTTOM_RIGHT", image.Width, image.Height);
				b.Save(newpath);
				b.Dispose();
				image.Dispose();
			}
			catch
			{
				if (File.Exists(oldpath))
				{
					File.Delete(oldpath);
				}
			}
			finally
			{
				if (File.Exists(oldpath))
				{
					File.Delete(oldpath);
				}
			}
		}




		/// <summary>
		///  加水印文字
		/// </summary>
		/// <param name="picture">imge 对象</param>
		/// <param name="_watermarkText">水印文字内容</param>
		/// <param name="_watermarkPosition">水印位置</param>
		/// <param name="_width">被加水印图片的宽</param>
		/// <param name="_height">被加水印图片的高</param>
		private static void addWatermarkText(Graphics picture, string watermarkText, string watermarkPosition, int width, int height)
		{
			// 确定水印文字的字体大小
			int[] sizes = new int[] { 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4 };
			Font crFont = null;
			SizeF crSize = new SizeF();
			for (int i = 0; i < sizes.Length; i++)
			{
				crFont = new Font("Arial Black", sizes[i], FontStyle.Bold);
				crSize = picture.MeasureString(watermarkText, crFont);

				if ((ushort)crSize.Width < (ushort)width) break;
			}

			// 生成水印图片（将文字写到图片中）
			Bitmap floatBmp = new Bitmap((int)crSize.Width + 3,
						   (int)crSize.Height + 3, PixelFormat.Format32bppArgb);
			Graphics fg = Graphics.FromImage(floatBmp);
			PointF pt = new PointF(0, 0);

			// 画阴影文字
			Brush TransparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black));
			Brush TransparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black));
			fg.DrawString(watermarkText, crFont, TransparentBrush0, pt.X, pt.Y + 1);
			fg.DrawString(watermarkText, crFont, TransparentBrush0, pt.X + 1, pt.Y);

			fg.DrawString(watermarkText, crFont, TransparentBrush1, pt.X + 1, pt.Y + 1);
			fg.DrawString(watermarkText, crFont, TransparentBrush1, pt.X, pt.Y + 2);
			fg.DrawString(watermarkText, crFont, TransparentBrush1, pt.X + 2, pt.Y);

			TransparentBrush0.Dispose();
			TransparentBrush1.Dispose();

			// 画文字
			fg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
			fg.DrawString(watermarkText,
				crFont, new SolidBrush(Color.White),
				pt.X, pt.Y, StringFormat.GenericDefault);

			// 保存刚才的操作
			fg.Save();
			fg.Dispose();
			// floatBmp.Save("d:\\WebSite\\DIGITALKM\\ttt.jpg");

			// 将水印图片加到原图中
			addWatermarkImage(picture, new Bitmap(floatBmp), "WM_BOTTOM_RIGHT", width,
				height);
		}

		/// <summary>
		///  加水印图片
		/// </summary>
		/// <param name="picture">imge 对象</param>
		/// <param name="iTheImage">Image对象（以此图片为水印）</param>
		/// <param name="_watermarkPosition">水印位置</param>
		/// <param name="_width">被加水印图片的宽</param>
		/// <param name="_height">被加水印图片的高</param>
		private static void addWatermarkImage(Graphics picture, Image iTheImage, string watermarkPosition, int width, int height)
		{
			Image watermark = new Bitmap(iTheImage);

			ImageAttributes imageAttributes = new ImageAttributes();
			ColorMap colorMap = new ColorMap();

			colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
			colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
			ColorMap[] remapTable = { colorMap };

			imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

			float[][] colorMatrixElements = {
                                                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
                                            };

			ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

			imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

			int xpos = 0;
			int ypos = 0;
			int WatermarkWidth = 0;
			int WatermarkHeight = 0;
			double bl = 1d;

			//计算水印图片的比率
			//取背景的1/4宽度来比较
			if ((width > watermark.Width * 4) && (height > watermark.Height * 4))
			{
				bl = 1;
			}
			else if ((width > watermark.Width * 4) && (height < watermark.Height * 4))
			{
				bl = Convert.ToDouble(height / 4) / Convert.ToDouble(watermark.Height);

			}
			else if ((width < watermark.Width * 4) && (height > watermark.Height * 4))
			{
				bl = Convert.ToDouble(width / 4) / Convert.ToDouble(watermark.Width);
			}
			else
			{
				if ((width * watermark.Height) > (height * watermark.Width))
				{
					bl = Convert.ToDouble(height / 4) / Convert.ToDouble(watermark.Height);

				}
				else
				{
					bl = Convert.ToDouble(width / 4) / Convert.ToDouble(watermark.Width);

				}

			}

			WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
			WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

			switch (watermarkPosition)
			{
				case "WM_TOP_LEFT":
					xpos = 10;
					ypos = 10;
					break;
				case "WM_TOP_RIGHT":
					xpos = width - WatermarkWidth - 10;
					ypos = 10;
					break;
				case "WM_BOTTOM_RIGHT":
					xpos = width - WatermarkWidth - 10;
					ypos = height - WatermarkHeight - 10;
					break;
				case "WM_BOTTOM_LEFT":
					xpos = 10;
					ypos = height - WatermarkHeight - 10;
					break;
			}

			picture.DrawImage(
				watermark,
				new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),
				0,
				0,
				watermark.Width,
				watermark.Height,
				GraphicsUnit.Pixel,
				imageAttributes);

			watermark.Dispose();
			imageAttributes.Dispose();
		}

		/// <summary>
		///  加水印图片
		/// </summary>
		/// <param name="picture">imge 对象</param>
		/// <param name="WaterMarkPicPath">水印图片的地址</param>
		/// <param name="_watermarkPosition">水印位置</param>
		/// <param name="_width">被加水印图片的宽</param>
		/// <param name="_height">被加水印图片的高</param>
		private static void addWatermarkImage(Graphics picture, string WaterMarkPicPath, string watermarkPosition, int width, int height)
		{
			Image watermark = new Bitmap(WaterMarkPicPath);
			addWatermarkImage(picture, watermark, watermarkPosition, width, height);
		}
		#endregion

		#region 生成缩略图
		/// <summary>
		/// 保存图片
		/// </summary>
		/// <param name="image">Image 对象</param>
		/// <param name="savePath">保存路径</param>
		/// <param name="ici">指定格式的编解码参数</param>
		private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
		{
			//设置 原图片 对象的 EncoderParameters 对象
			EncoderParameters parameters = new EncoderParameters(1);
			parameters.Param[0] = new EncoderParameter(
				System.Drawing.Imaging.Encoder.Quality, ((long)90));
			image.Save(savePath, ici, parameters);
			parameters.Dispose();
		}

		/// <summary>
		/// 获取图像编码解码器的所有相关信息
		/// </summary>
		/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
		/// <returns>返回图像编码解码器的所有相关信息</returns>
		private static ImageCodecInfo GetCodecInfo(string mimeType)
		{
			ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
			foreach (ImageCodecInfo ici in CodecInfo)
			{
				if (ici.MimeType == mimeType)
					return ici;
			}
			return null;
		}

		/// <summary>
		/// 生成缩略图
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="thumbnailImageWidth">缩略图的宽度（高度与按源图片比例自动生成）</param>
		public static void ToThumbnailImages(string SourceImagePath, string ThumbnailImagePath, int ThumbnailImageWidth)
		{
			Hashtable htmimes = new Hashtable();
			htmimes[".jpeg"] = "image/jpeg";
			htmimes[".jpg"] = "image/jpeg";
			htmimes[".png"] = "image/png";
			htmimes[".tif"] = "image/tiff";
			htmimes[".tiff"] = "image/tiff";
			htmimes[".bmp"] = "image/bmp";
			htmimes[".gif"] = "image/gif";

			// 取得原图片的后缀
			string sExt = SourceImagePath.Substring(
				SourceImagePath.LastIndexOf(".")).ToLower();

			//从 原图片 创建 Image 对象
			Image image = Image.FromFile(SourceImagePath);
			int num = ((ThumbnailImageWidth / 4) * 3);
			int width = image.Width;
			int height = image.Height;

			//计算图片的比例
			if ((((double)width) / ((double)height)) >= 1.3333333333333333f)
			{
				num = ((height * ThumbnailImageWidth) / width);
			}
			else
			{
				ThumbnailImageWidth = ((width * num) / height);
			}
			if ((ThumbnailImageWidth < 1) || (num < 1))
			{
				return;
			}

			//用指定的大小和格式初始化 Bitmap 类的新实例
			Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,
				PixelFormat.Format32bppArgb);

			//从指定的 Image 对象创建新 Graphics 对象
			Graphics graphics = Graphics.FromImage(bitmap);

			//清除整个绘图面并以透明背景色填充
			graphics.Clear(Color.Transparent);

			graphics.SmoothingMode = SmoothingMode.HighQuality;
			graphics.InterpolationMode = InterpolationMode.High;

			//在指定位置并且按指定大小绘制 原图片 对象
			graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
			image.Dispose();

			try
			{
				//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 
				SaveImage(bitmap, ThumbnailImagePath,
					GetCodecInfo((string)htmimes[sExt]));
			}
			catch (System.Exception e)
			{
				throw e;
			}
		}

		/// <summary>
		/// 生成Jpg缩略图
		/// </summary>
		/// <param name="originalImagePath">源图路径（物理路径）</param>
		/// <param name="thumbnailPath">缩略图路径（物理路径）</param>
		/// <param name="width">缩略图宽度</param>
		/// <param name="height">缩略图高度</param>
		/// <param name="mode">生成缩略图的方式</param>    
		public static void ToThumbnailImages(string SourceImagePath, string ThumbnailImagePath, int width, int height, ThumbnailMode mode)
		{
			Image originalImage = Image.FromFile(SourceImagePath);

			int towidth = width;
			int toheight = height;

			int x = 0;
			int y = 0;
			int ow = originalImage.Width;
			int oh = originalImage.Height;

			switch (mode)
			{
				case ThumbnailMode.AutoHeight: //指定宽，高按比例                    
					toheight = originalImage.Height * width / originalImage.Width;
					break;
				case ThumbnailMode.AutoWith: //指定高，宽按比例
					towidth = originalImage.Width * height / originalImage.Height;
					break;
				case ThumbnailMode.Cut: //指定高宽裁减（不变形）                
					if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
					{
						oh = originalImage.Height;
						ow = originalImage.Height * towidth / toheight;
						y = 0;
						x = (originalImage.Width - ow) / 2;
					}
					else
					{
						ow = originalImage.Width;
						oh = originalImage.Width * height / towidth;
						x = 0;
						y = (originalImage.Height - oh) / 2;
					}
					break;
				case ThumbnailMode.AutoFit: //指定高宽缩放（可能变形）                
					break;
				default:
					break;
			}

			//新建一个bmp图片
			Image bitmap = new Bitmap(towidth, toheight);

			//新建一个画板
			Graphics g = Graphics.FromImage(bitmap);

			//设置高质量插值法
			g.InterpolationMode = InterpolationMode.High;

			//设置高质量,低速度呈现平滑程度
			g.SmoothingMode = SmoothingMode.HighQuality;

			//清空画布并以透明背景色填充
			g.Clear(Color.Transparent);

			//在指定位置并且按指定大小绘制原图片的指定部分
			g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
						new Rectangle(x, y, ow, oh),
						GraphicsUnit.Pixel);

			try
			{
				//以jpg格式保存缩略图
				bitmap.Save(ThumbnailImagePath, ImageFormat.Jpeg);
			}
			catch (Exception e)
			{
				throw e;
			}
			finally
			{
				originalImage.Dispose();
				bitmap.Dispose();
				g.Dispose();
			}
		}

		private static Bitmap MakeThumbnail(System.Drawing.Image fromImg, int width, int height)
		{
			Bitmap bmp = new Bitmap(width, height);
			int ow = fromImg.Width;
			int oh = fromImg.Height;

			//新建一个画板
			Graphics g = Graphics.FromImage(bmp);

			//设置高质量插值法
			g.InterpolationMode = InterpolationMode.High;
			//设置高质量,低速度呈现平滑程度
			g.SmoothingMode = SmoothingMode.Default;
			//清空画布并以透明背景色填充
			g.Clear(Color.White);

			g.DrawImage(fromImg, new Rectangle(0, 0, width, height),
				new Rectangle(0, 0, ow, oh),
				GraphicsUnit.Pixel);

			return bmp;

		}

		private static bool SaveCutPic(string pPath, string filePath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
		{

			using (System.Drawing.Image originalImg = System.Drawing.Image.FromFile(pPath))
			{
				try
				{
					Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
					Graphics graphics = Graphics.FromImage(partImg);
					Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
					Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）

					///注释 文字水印  
					Graphics G = Graphics.FromImage(partImg);
					//Font f = new Font("Lucida Grande", 6);
					//Brush b = new SolidBrush(Color.Gray);
					G.Clear(Color.White);
					// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
					G.InterpolationMode = InterpolationMode.HighQualityBicubic;
					// 指定高质量、低速度呈现。 
					G.SmoothingMode = SmoothingMode.HighQuality;

					graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
					//G.DrawString("Xuanye", f, b, 0, 0);
					G.Dispose();

					originalImg.Dispose();
					if (File.Exists(filePath))
					{
						File.SetAttributes(filePath, FileAttributes.Normal);
						File.Delete(filePath);
					}
					partImg.Save(filePath, ImageFormat.Jpeg);
					partImg.Dispose();
				}
				catch
				{
					return false;
				}
			}
			return true;
		}


		public static string SaveCutPic(string srcImageFile, string dPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
		{
			//string filePath;
			string fullname = srcImageFile.GetRandomFileName(dPath);

			using (System.Drawing.Image originalImg = System.Drawing.Image.FromFile(srcImageFile))
			{
				try
				{
					if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
					{
						return SaveCutPic(srcImageFile, fullname, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight,
							pOrigStartPointX, pOrigStartPointY) ? fullname : "";

					}

					Bitmap thumimg = MakeThumbnail(originalImg, imageWidth, imageHeight);

					Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);

					Graphics graphics = Graphics.FromImage(partImg);
					Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
					Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）

					///文字水印  
					Graphics G = Graphics.FromImage(partImg);
					//Font f = new Font("Lucida Grande", 6);
					//Brush b = new SolidBrush(Color.Gray);
					G.Clear(Color.White);
					// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
					G.InterpolationMode = InterpolationMode.HighQualityBicubic;
					// 指定高质量、低速度呈现。 
					G.SmoothingMode = SmoothingMode.HighQuality;

					graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
					//G.DrawString("Xuanye", f, b, 0, 0);
					G.Dispose();

					originalImg.Dispose();
					//if (File.Exists(HttpContext.Current.Server.MapPath(fullname)))
					//{
					//    File.SetAttributes(HttpContext.Current.Server.MapPath(fullname), FileAttributes.Normal);
					//    File.Delete(HttpContext.Current.Server.MapPath(fullname));
					//}
					partImg.Save(fullname, ImageFormat.Jpeg);

					partImg.Dispose();
					thumimg.Dispose();
				}
				catch
				{
					return "";
				}
				return fullname;
			}
		}


		#endregion

	}
}
